package com.chenjt.juc.three_completableFuture;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * 注释：
 *
 * @author chenjt
 * @date 2024/7/6 11:41
 */
public class CompletableFutureAPI2Demo {

    public static void main(String[] args) {

//        thenApply();

        handle();


    }


    /**
     * thenApply有异常时不会往下走
     */
    private static void thenApply() {

        ExecutorService threadPool = Executors.newFixedThreadPool(3);

        CompletableFuture.supplyAsync(()->{
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return 1;
        },threadPool).thenApply(f->{
            int i = 1/0;
            System.out.println("222");
            return f + 2;
        }).thenApply(f->{
            System.out.println("333");
            return f + 3;
        }).whenComplete((v,e)->{
            if(e == null){
                System.out.println("计算结果：" + v);
            }
        }).exceptionally(e->{
            e.printStackTrace();
            System.out.println(e.getMessage());
            return null;
        });

        System.out.println(Thread.currentThread().getName() + "主线程先去忙其他任务");

        threadPool.shutdown();

    }


    /**
     * handle有异常时会往下走
     */
    private static void handle() {
        ExecutorService threadPool = Executors.newFixedThreadPool(3);

        CompletableFuture.supplyAsync(()->{
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return 1;
        },threadPool).handle((f,e)->{
            int i = 1/0;
            System.out.println("222");
            return f + 2;
        }).handle((f,e)->{
            System.out.println("333");
            return f + 3;
        }).whenComplete((v,e)->{
            if(e == null){
                System.out.println("计算结果：" + v);
            }
        }).exceptionally(e->{
            e.printStackTrace();
            System.out.println(e.getMessage());
            return null;
        });

        System.out.println(Thread.currentThread().getName() + "主线程先去忙其他任务");

        threadPool.shutdown();
    }

}
